package net.zoneland.knowledge.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 获取spring容器，以访问容器中定义的其他bean
 * 
 * @author ypz
 * @version $Id: SpringContextUtil.java, v 0.1 2013-5-8 下午2:10:09 ypz Exp $
 */
@Component
public class SpringContextUtil implements ApplicationContextAware {

    private static final Logger logger = LoggerFactory.getLogger(SpringContextUtil.class);

    /**
     *  Spring应用上下文环境.
     */
    private static ApplicationContext applicationContext;

    /**
     * 实现ApplicationContextAware接口的回调方法，设置上下文环境
     * 
     * @param applicationContext
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        SpringContextUtil.applicationContext = applicationContext;
    }

    /**
     * @return ApplicationContext
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 根据beanName获取对象
     * 
     * @param name
     * @return Object 一个以所给名字注册的bean的实例，如果bean不存在，返回null
     */
    public static Object getBean(String name) {
        Object beanObject = null;
        try {
            beanObject = applicationContext.getBean(name);
        } catch (BeansException e) {
            logger.error("获取Spring bean异常", e);
        }
        return beanObject;
    }

    /**
     * 根据类型获取对象
     * 
     * @param classType
     * @return Object 一个以所给名字注册的bean的实例，如果bean不存在，返回null
     */
    public static <T> T getBean(Class<T> classType) {
        T beanObject = null;
        try {
            beanObject = applicationContext.getBean(classType);
        } catch (BeansException e) {
            logger.error("获取Spring bean异常", e);
        }
        return beanObject;
    }

    /**
     * 根据类型获取对象
     * 
     * @param beanName
     * @return Object 一个以所给名字注册的bean的实例，如果bean不存在，返回null
     */
    public static Object getBeanByName(String beanName) {
        Object obj = null;
        try {
            obj = applicationContext.getBean(beanName);
        } catch (BeansException e) {
            logger.error("获取Spring bean异常", e);
        }
        return obj;
    }

}
